use crate::dto::*;
use crate::entity::*;
use crate::RB;
use hypers::prelude::{hypers_openapi, openapi, OpenApi, Responder, Response};
use rbatis::rbdc::datetime::DateTime;
use rbatis::plugin::page::PageRequest;

pub struct Types;

#[openapi(
    prefix = "/api",
    components(schemas(TypesSaveReq, TypesDeleteReq, TypesUpdateReq, TypesListReq))
)]
impl Types {
    #[post("types_save",tag = "添加题目类型",request_body = TypesSaveReq)]
    async fn types_save(item: TypesSaveReq) -> impl Responder {
        log::info!("types_save params: {:?}", &item);
        let types = InterviewTypes {
            id: None,
            interview_code: item.interview_code,
            create_time: Some(DateTime::now()),
            update_time: Some(DateTime::now()),
        };
        let result = InterviewTypes::insert(&mut RB.clone(), &types).await;
        handle_result(result)
    }
    
    #[post("types_delete",tag = "删除题目类型",request_body = TypesDeleteReq)]
    async fn types_delete(item: TypesDeleteReq) -> impl Responder {
        log::info!("types_delete params: {:?}", &item);
        let result = InterviewTypes::delete_in_column(&mut RB.clone(), "id", &item.ids).await;
        handle_result(result)
    }

    #[post("types_update",tag = "更新题目类型",request_body = TypesUpdateReq)]
    async fn types_update(item: TypesUpdateReq) -> impl Responder {
        log::info!("types_update params: {:?}", &item);
        let types = InterviewTypes {
            id: item.id,
            interview_code: item.interview_code,
            create_time: None,
            update_time: Some(DateTime::now()),
        };
        let result = InterviewTypes::update_by_column(&mut RB.clone(), &types, "id").await;
        handle_result(result)
    }

    #[post("types_list",tag = "查询题目类型",request_body = TypesListReq)]
    async fn types_list(item: TypesListReq) -> impl Responder {
        log::info!("types_list params: {:?}", &item);
        let page = &PageRequest::new(item.page_no, item.page_size);
        let result = InterviewTypes::select_page(&mut RB.clone(), page).await;
        let mut res = Response::default();
        match result {
            Ok(d) => {
                let mut types_list_data: Vec<TypesListData> = Vec::new();
                for x in d.records {
                    types_list_data.push(TypesListData {
                        id: x.id,
                        interview_code: x.interview_code,
                        create_time: x.create_time.unwrap().0.to_string(),
                        update_time: x.update_time.unwrap().0.to_string(),
                    })
                }
                res.json(&ok_result_page(types_list_data, d.total));
                res
            }
            Err(err) => {
                log::error!("{}", err.to_string());
                res.json(&err_result_page(err.to_string()));
                res
            }
        }
    }
}
